package xzap

import (
	"fmt"

	"gitlab-tech.shruisong.cn/growth/go-common/pkg/utils"
	"go.uber.org/zap/zapcore"
)

type alertCore struct {
	zapcore.LevelEnabler
	enc zapcore.Encoder
}

func (c *alertCore) With(fields []zapcore.Field) zapcore.Core {
	clone := c.clone()
	addFields(clone.enc, fields)
	return clone
}

func (c *alertCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
	if c.Enabled(ent.Level) {
		return ce.AddCore(ent, c)
	}

	return ce
}

func (c *alertCore) Write(ent zapcore.Entry, fields []zapcore.Field) error {
	// 发微信消息
	if c.Enabled(ent.Level) == false {
		return nil
	}

	buf, err := c.enc.EncodeEntry(ent, fields)
	if err != nil {
		return err
	}
	utils.SendWorkWechatMsg(buf.String())
	return nil
}

func (c *alertCore) Sync() error {
	return nil
}

func (c *alertCore) clone() *alertCore {
	return &alertCore{
		LevelEnabler: c.LevelEnabler,
		enc:          c.enc,
	}
}

func (c *alertCore) alertMsg(ent zapcore.Entry) error {
	if c.Enabled(ent.Level) == false {
		return nil
	}

	msg := "File: %s, Err: %s, Stack: %s"
	msg = fmt.Sprintf(msg, ent.Caller.String(), ent.Message, ent.Stack)
	utils.SendWorkWechatMsg(msg)
	return nil
}

func (c *alertCore) Enabled(lvl zapcore.Level) bool {
	//c.level = lvl
	return lvl > zapcore.ErrorLevel
}
